package no.ntnu.fp.connection;

import java.util.HashMap;
import java.util.Map;

import no.ntnu.fp.exceptions.UnsupportedMessageException;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.MessageCode;

/**
 * A class used to handle messages received by a {@link ReceiveWorker}.
 * Designed as a singleton to ease sharing of it between different {@code ReceiveWorker}s.
 * @author benjamin
 *
 */
final class MessageHandler {
	private final MessageTranslator messageTranslator = MessageTranslator.getInstance();
	private final Map<MessageCode, Handler> map = new HashMap<MessageCode, Handler>();
	
	public void handleMessage(String msg) {
		Message message = messageTranslator.translateMessage(msg);
		Handler handler = map.get(message.getMessageCode());
		if (handler == null) {
			throw new UnsupportedMessageException(
					"No handler registered for message code", message.getMessageCode());
		}
		handler.handleMessage(message);
	}

	
	private static MessageHandler instance;
	
	public synchronized static MessageHandler createInstance(Map<MessageCode, Handler> map) {
		if (instance == null) {
			instance = new MessageHandler();
			instance.map.putAll(map);
			return instance;
		} else {
			throw new IllegalStateException("MessageHandler is already initialized");
		}
	}
	
	public synchronized static MessageHandler getInstance() {
		if (instance == null) {
			throw new IllegalStateException("MessageHandler is not initialized");
		}
		return instance;
	}
	
	private MessageHandler() { }
}
